/*
 * Copyright (c) 田梓萱 2021-2022.
 * All Rights Reserved.
 * All codes are protected by China's regulations on the protection of computer software, and infringement must be investigated.
 * 版权所有 (c) 田梓萱 2021-2022.
 * 所有代码均受中国《计算机软件保护条例》保护，本项目已获得软著.
 */

package com.xcl.calculator.slice.Calculate;

import com.huawei.agconnect.crash.AGConnectCrash;
import com.net.jianjia.Call;
import com.net.jianjia.Callback;
import com.net.jianjia.Response;
import com.xcl.calculator.DataANet.Convert;
import com.xcl.calculator.Dialog.MyToastDialog;
import com.xcl.calculator.MyApplication;
import com.xcl.calculator.Net.NetStatusCallback;
import com.xcl.calculator.Preference_RW;
import com.xcl.calculator.ResourceTable;
import com.xcl.calculator.XLog;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.Button;
import ohos.agp.components.Component;
import ohos.agp.components.Picker;
import ohos.agp.components.Text;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.service.WindowManager;
import ohos.data.distributed.common.KvManagerConfig;
import ohos.data.distributed.common.KvManagerFactory;
import ohos.distributedhardware.devicemanager.DeviceInfo;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.multimodalinput.event.KeyEvent;
import ohos.multimodalinput.event.MmiPoint;
import ohos.multimodalinput.event.TouchEvent;
import ohos.net.NetManager;
import ohos.utils.PacMap;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import static com.xcl.calculator.MyApplication.instance_hi;
import static java.util.regex.Pattern.compile;

/**
 * The type Hui lv ability slice.
 *
 * @author Xcl
 * @date 2022 /2/18
 * @package com.xcl.calculator.slice.Calculate
 */
public class HuiLvAbilitySlice extends AbilitySlice implements Component.TouchEventListener {
    /**
     * The constant label.
     */
    private static final HiLogLabel label = new HiLogLabel(HiLog.LOG_APP, 0x00234, "HuiLvAbilitySlice");
    /**
     * The constant stringTitle.
     */
    private static final String[] stringTitle = {"AED",
            "AFN",
            "ALL",
            "AMD",
            "ANG",
            "AOA",
            "ARS",
            "AUD",
            "AWG",
            "AZN",
            "BAM",
            "BBD",
            "BDT",
            "BGN",
            "BHD",
            "BIF",
            "BMD",
            "BND",
            "BOB",
            "BRL",
            "BSD",
            "BTC",
            "BTN",
            "BWP",
            "BYN",
            "BZD",
            "CAD",
            "CDF",
            "CHF",
            "CLF",
            "CLP",
            "CNH",
            "CNY",
            "COP",
            "CRC",
            "CUC",
            "CUP",
            "CVE",
            "CZK",
            "DJF",
            "DKK",
            "DOP",
            "DZD",
            "EGP",
            "ERN",
            "ETB",
            "EUR",
            "FJD",
            "FKP",
            "GBP",
            "GEL",
            "GGP",
            "GHS",
            "GIP",
            "GMD",
            "GNF",
            "GTQ",
            "GYD",
            "HKD",
            "HNL",
            "HRK",
            "HTG",
            "HUF",
            "IDR",
            "ILS",
            "IMP",
            "INR",
            "IQD",
            "IRR",
            "ISK",
            "JEP",
            "JMD",
            "JOD",
            "JPY",
            "KES",
            "KGS",
            "KHR",
            "KMF",
            "KPW",
            "KRW",
            "KWD",
            "KYD",
            "KZT",
            "LAK",
            "LBP",
            "LKR",
            "LRD",
            "LSL",
            "LYD",
            "MAD",
            "MDL",
            "MGA",
            "MKD",
            "MMK",
            "MNT",
            "MOP",
            "MRO",
            "MRU",
            "MUR",
            "MVR",
            "MWK",
            "MXN",
            "MYR",
            "MZN",
            "NAD",
            "NGN",
            "NIO",
            "NOK",
            "NPR",
            "NZD",
            "OMR",
            "PAB",
            "PEN",
            "PGK",
            "PHP",
            "PKR",
            "PLN",
            "PYG",
            "QAR",
            "RON",
            "RSD",
            "RUB",
            "RWF",
            "SAR",
            "SBD",
            "SCR",
            "SDG",
            "SEK",
            "SGD",
            "SHP",
            "SLL",
            "SOS",
            "SRD",
            "SSP",
            "STD",
            "STN",
            "SVC",
            "SYP",
            "SZL",
            "THB",
            "TJS",
            "TMT",
            "TND",
            "TOP",
            "TRY",
            "TTD",
            "TWD",
            "TZS",
            "UAH",
            "UGX",
            "USD",
            "UYU",
            "UZS",
            "VEF",
            "VES",
            "VND",
            "VUV",
            "WST",
            "XAF",
            "XAG",
            "XAU",
            "XCD",
            "XDR",
            "XOF",
            "XPD",
            "XPF",
            "XPT",
            "YER",
            "ZAR",
            "ZMW",
            "ZWL"};
    /**
     * The constant ansm.
     */
    private static String ansm = null;
    /**
     * The constant ansm1.
     */
    private static String ansm1 = null;
    /**
     * The constant dw1.
     */
    private static int dw1 = -1;
    /**
     * The constant dw2.
     */
    private static int dw2 = -1;
    /**
     * The constant panduan.
     */
    private static int panduan = 0;
    /**
     * The M net status callback.
     */
    private final NetStatusCallback mNetStatusCallback = new NetStatusCallback();
    /**
     * The Dw.
     */
    private int dw = -1;
    /**
     * The Quemo.
     */
    private Text quemo;
    /**
     * The Ansmo.
     */
    private Text ansmo;
    /**
     * The Picker.
     */
    private Picker picker;
    /**
     * The Net manager.
     */
//AGConnectConfig config = AGConnectConfig.getInstance();//TODO：远程配置
    private NetManager netManager;
    /**
     * The Starx.
     */
    private float starx;
    /**
     * The Stary.
     */
    private float stary;
    /**
     * The Endx.
     */
    private float endx;
    /**
     * The Endy.
     */
    private float endy;

    /**
     * Is decimal boolean.
     *
     * @param que the que
     * @return the boolean
     */
    private static boolean isDecimal(String que) {
        Pattern pattern = compile("[0-9]*");
        if (que.indexOf(".") > 0) if (que.indexOf(".") == que.lastIndexOf(".") && que.split("\\.").length == 2)
            return pattern.matcher(que.replace(".", "")).matches();
        else return false;
        else return pattern.matcher(que).matches();
    }

    /**
     * Get method.
     *
     * @param a1 the a 1
     * @param a2 the a 2
     * @param a3 the a 3
     * @param a4 the a 4
     */
//TODO:https://api.xuegao-xcl.tech/convert?from=FJD&to=SCR&amount=100&source=boc
    private void GetMethod(String a1, String a2, String a3, String a4) {
        try {
            this.ansmo.setText("计算中...");
            this.ansmo.setTextColor(Color.YELLOW);
            Map<String, String> url = new HashMap<String, String>();
            url.put("from", a2);
            url.put("to", a3);
            url.put("amount", a1);
            url.put("source", a4);
            Map<String, String> url1 = new HashMap<String, String>();
            url1.put("from", a2);
            url1.put("to", a3);
            url1.put("amount", a1);
            MyApplication.getInstance().getWan().getMoney(url).enqueue(new Callback<Convert>() {
                @Override
                public void onResponse(Call<Convert> call, Response<Convert> response) {
                    if (response.isSuccessful()) {
                        // 请求成功
                        HuiLvAbilitySlice.ansm1 = response.body().result;
                        if ("".equals(HuiLvAbilitySlice.ansm1) || HuiLvAbilitySlice.ansm1 == null || "null".equals(HuiLvAbilitySlice.ansm1)) {
                            HuiLvAbilitySlice.this.ShowDialog1("非常用货币单位，正在飞速计算中，请耐心等待...");
                            MyApplication.getInstance().getWan().getMoney(url1).enqueue(new Callback<Convert>() {
                                @Override
                                public void onResponse(Call<Convert> call, Response<Convert> response) {
                                    if (response.isSuccessful()) {
                                        // 请求成功
                                        XLog.info(HuiLvAbilitySlice.label, "[3]" + response.body().result);
                                        HuiLvAbilitySlice.ansm = response.body().result;
                                        //TODO:自定义埋点，在工程合适位置插入埋点代码
                                        PacMap pacMap = new PacMap();
                                        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                                        pacMap.putString("user_uuid", "[" + Preference_RW.uuid.toString() + "]");
                                        pacMap.putString("start_num", "[" + HuiLvAbilitySlice.this.quemo.getText() + "],货币单位:[" + a2 + "]");
                                        pacMap.putString("end_num", "[" + HuiLvAbilitySlice.ansm + "],货币单位:[" + a3 + "]");
                                        pacMap.putString("se_time", "[" + df.format(new Date()) + "]");
                                        instance_hi.onEvent("currency", pacMap);
                                        HuiLvAbilitySlice.this.getUITaskDispatcher().asyncDispatch(new Runnable() {
                                            @Override
                                            public void run() {
                                                HuiLvAbilitySlice.this.ansmo.setText(HuiLvAbilitySlice.ansm);
                                                HuiLvAbilitySlice.this.ansmo.setTextColor(Color.WHITE);
                                            }
                                        });
                                    } else {
                                        HuiLvAbilitySlice.this.getUITaskDispatcher().asyncDispatch(new Runnable() {
                                            @Override
                                            public void run() {
                                                HuiLvAbilitySlice.this.ansmo.setText("计算失败!");
                                                HuiLvAbilitySlice.this.ShowDialog2("接口故障，无法获取汇率，无法计算!");
                                                HuiLvAbilitySlice.this.ansmo.setTextColor(Color.WHITE);
                                            }
                                        });
                                        XLog.warn(HuiLvAbilitySlice.label, "接口故障，错误代码:" + response.code());
                                    }
                                }

                                @Override
                                public void onFailure(Call<Convert> call, Throwable t) {
                                    // 请求失败
                                    HuiLvAbilitySlice.this.getUITaskDispatcher().asyncDispatch(new Runnable() {
                                        @Override
                                        public void run() {
                                            HuiLvAbilitySlice.this.ansmo.setText("计算失败!");
                                            HuiLvAbilitySlice.this.ShowDialog2("网络错误，无法获取汇率，无法计算!");
                                            HuiLvAbilitySlice.this.ansmo.setTextColor(Color.WHITE);
                                        }
                                    });
                                    AGConnectCrash.getInstance().recordException(t);
                                    XLog.error(HuiLvAbilitySlice.label, t.getMessage());
                                }
                            });
                        } else {
                            //TODO:自定义埋点，在工程合适位置插入埋点代码
                            PacMap pacMap = new PacMap();
                            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
                            pacMap.putString("user_uuid", "[" + Preference_RW.uuid.toString() + "]");
                            pacMap.putString("start_num", "[" + HuiLvAbilitySlice.this.quemo.getText() + "],货币单位:[" + a2 + "]");
                            pacMap.putString("end_num", "[" + HuiLvAbilitySlice.ansm1 + "],货币单位:[" + a3 + "]");
                            pacMap.putString("se_time", "[" + df.format(new Date()) + "]");
                            instance_hi.onEvent("currency", pacMap);
                            HuiLvAbilitySlice.this.getUITaskDispatcher().asyncDispatch(new Runnable() {
                                @Override
                                public void run() {
                                    HuiLvAbilitySlice.this.ansmo.setText(HuiLvAbilitySlice.ansm1);
                                    HuiLvAbilitySlice.this.ansmo.setTextColor(Color.WHITE);
                                }
                            });
                        }

                    } else {
                        HuiLvAbilitySlice.this.getUITaskDispatcher().asyncDispatch(new Runnable() {
                            @Override
                            public void run() {
                                HuiLvAbilitySlice.this.ansmo.setText("计算失败!");
                                HuiLvAbilitySlice.this.ShowDialog2("接口故障，无法获取汇率，无法计算!");
                                HuiLvAbilitySlice.this.ansmo.setTextColor(Color.WHITE);
                            }
                        });
                        XLog.warn(HuiLvAbilitySlice.label, "接口故障，错误代码:" + response.code());
                    }
                }

                @Override
                public void onFailure(Call<Convert> call, Throwable t) {
                    // 请求失败
                    HuiLvAbilitySlice.this.getUITaskDispatcher().asyncDispatch(new Runnable() {
                        @Override
                        public void run() {
                            HuiLvAbilitySlice.this.ansmo.setText("计算失败!");
                            HuiLvAbilitySlice.this.ShowDialog2("网络错误，无法获取汇率，无法计算!");
                            HuiLvAbilitySlice.this.ansmo.setTextColor(Color.WHITE);
                        }
                    });
                    AGConnectCrash.getInstance().recordException(t);
                    XLog.error(HuiLvAbilitySlice.label, t.getMessage());
                }
            });
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * On start.
     *
     * @param intent the intent
     */
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        try {
            XLog.pd_pd = Preference_RW.ff7_r();
            this.getWindow().addFlags(WindowManager.LayoutConfig.MARK_ALLOW_EXTEND_LAYOUT);
            ohos.data.distributed.device.DeviceInfo localDeviceInfo = KvManagerFactory.getInstance()
                    .createKvManager(new KvManagerConfig((this))).getLocalDeviceInfo();
            int localDeviceType = Integer.parseInt(localDeviceInfo.getType());
            if (localDeviceType == DeviceInfo.DeviceType.PHONE.value()) {
                this.setUIContent(ResourceTable.Layout_hlzhm);
                XLog.info(label, "当前设备类型为手机");
            } else if (localDeviceType == DeviceInfo.DeviceType.TABLET.value()) {
                this.setUIContent(ResourceTable.Layout_hlzht);
                XLog.info(label, "当前设备类型为平板");
            } else {
                XLog.warn(label, "暂不支持您的设备:(" + localDeviceInfo.getType() + ")");
                this.terminateAbility();
            }
            this.quemo = (Text) this.findComponentById(ResourceTable.Id_gg1_field);
            this.ansmo = (Text) this.findComponentById(ResourceTable.Id_gg3_field);
            this.quemo.setText("原数值");
            this.ansmo.setText("结果值");
            Text xinxi = (Text) this.findComponentById(ResourceTable.Id_danwei);
            xinxi.setText("货币单位");
            this.findComponentById(ResourceTable.Id_show0).setTouchEventListener(this);
            this.prepareButtons();
            this.picker = (Picker) this.findComponentById(ResourceTable.Id_dw_picker);
            this.picker.setBindStateChangedListener(new Component.BindStateChangedListener() {
                @Override
                public void onComponentBoundToWindow(Component component) {
                    component.setTouchFocusable(true);
                    component.setVibrationEffectEnabled(true);
                    component.requestFocus();
                }

                @Override
                public void onComponentUnboundFromWindow(Component component) {
                }
            });
            this.picker.setDisplayedData(stringTitle);
            this.picker.setMinValue(0);
            this.picker.setValueChangedListener(new Picker.ValueChangedListener() {
                @Override
                public void onValueChanged(Picker picker, int i, int i1) {
                    if (i1 >= 0 && i1 < HuiLvAbilitySlice.stringTitle.length) {
                        picker.setMinValue(0);
                        picker.setDisplayedData(HuiLvAbilitySlice.stringTitle);
                        picker.setMaxValue(HuiLvAbilitySlice.stringTitle.length - 1);
                    }
                    HuiLvAbilitySlice.this.dw = i1;
                }
            });
            //TODO：对接主程序时注意在切换至此界面时判断当前设备网络状态，无网络链接就不跳转了
            //TODO:--------------开始
            /**
             * 网络是否连接，true表示网络已经连接，但未必可以上网，
             * 有时我们连接了一个网络，但由于网络已经到期（该交钱了）或者使用的代理不可用，
             * 设备虽然连接了网络，但是不能上网
             *
             boolean networkConnect = NetworkUtil.isNetworkConnected(this);
             XLog.info(label, "网络已连接" + String.valueOf(networkConnect));
             // 是否是WiFi连接，只要是WiFi连接，就返回true，不管能不能上网。
             boolean wifiConnected = NetworkUtil.isWifiConnected(this);
             XLog.info(label, String.valueOf(wifiConnected));
             // 否是数据网络连接，只要是数据网络连接，就返回true，不管能不能上网
             boolean mobileConnected = NetworkUtil.isMobileConnected(this);
             XLog.info(label, String.valueOf(mobileConnected));
             // 网络是否连接，true表示网络已经连接，并且可以上网
             boolean networkConnectedInternet = NetworkUtil.isNetworkConnectedInternet(this);
             XLog.info(label, "可以正常上网！" + String.valueOf(networkConnectedInternet));
             // 是否是WiFi连接，true表示WiFi连接，并且可以上网
             boolean wifiConnectedInternet = NetworkUtil.isWifiConnectedInternet(this);
             XLog.info(label, String.valueOf(wifiConnectedInternet));
             // 是否是数据网络连接，true表示数据网络连接，并且可以上网
             boolean mobileConnectedInternet = NetworkUtil.isMobileConnectedInternet(this);
             XLog.info(label, "数据连接，注意流量消耗！" + String.valueOf(mobileConnectedInternet));
             //TODO:--------------结束
             **
             * 下面的代码用于获取实时的网络状态。用户可以随时打开或者关闭网络，当用户打开或者关闭网络时，
             * 我们可以获取实时的网络状态
             */
            // 获取网络管理对象
            this.netManager = NetManager.getInstance(this);
            // 添加监听，监听实时的网络状态
            this.netManager.addDefaultNetStatusCallback(this.mNetStatusCallback);
            this.findComponentById(ResourceTable.Id_jback_button).setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component v) {
                    XLog.info(HuiLvAbilitySlice.label, "回退");
                    HuiLvAbilitySlice.this.ansmo.setHint("结果值");
                    HuiLvAbilitySlice.this.ansmo.setHintColor(Color.GRAY);
                    String current = HuiLvAbilitySlice.this.quemo.getText();
                    if (current.length() > 0)
                        HuiLvAbilitySlice.this.quemo.setText(current.substring(0, current.length() - 1));
                }
            });//撤回
            this.findComponentById(ResourceTable.Id_jac_button).setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component v) {
                    XLog.info(HuiLvAbilitySlice.label, "清空");
                    HuiLvAbilitySlice.this.ansmo.setHint("结果值");
                    HuiLvAbilitySlice.this.ansmo.setHintColor(Color.GRAY);
                    Text q2 = (Text) HuiLvAbilitySlice.this.findComponentById(ResourceTable.Id_gg2_field);
                    Text q4 = (Text) HuiLvAbilitySlice.this.findComponentById(ResourceTable.Id_gg4_field);
                    if (HuiLvAbilitySlice.panduan == 1) {
                        HuiLvAbilitySlice.this.quemo.setText("原数值");
                        q2.setText("原数单位");
                        HuiLvAbilitySlice.this.ansmo.setText("结果值");
                        q4.setText("结果单位");
                        HuiLvAbilitySlice.panduan = 4;
                    } else {
                        HuiLvAbilitySlice.this.quemo.setText("原数值");
                        HuiLvAbilitySlice.this.ansmo.setText("结果值");
                        HuiLvAbilitySlice.panduan = 4;
                    }
                }
            });//清空
            this.findComponentById(ResourceTable.Id_jj1_button).setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component v) {
                    HuiLvAbilitySlice.this.ansmo.setHint("结果值");
                    HuiLvAbilitySlice.this.ansmo.setHintColor(Color.GRAY);
                    HuiLvAbilitySlice.dw1 = HuiLvAbilitySlice.this.dw;
                    Text que1 = (Text) HuiLvAbilitySlice.this.findComponentById(ResourceTable.Id_gg2_field);
                    if (HuiLvAbilitySlice.dw1 == -1) {
                        HuiLvAbilitySlice.dw1 = 1;
                        que1.setText(HuiLvAbilitySlice.stringTitle[HuiLvAbilitySlice.dw1]);
                    } else que1.setText(HuiLvAbilitySlice.stringTitle[HuiLvAbilitySlice.dw1]);
                    HuiLvAbilitySlice.panduan = 2;
                }
            });//gg1
            this.findComponentById(ResourceTable.Id_jj2_button).setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component v) {
                    HuiLvAbilitySlice.this.ansmo.setHint("结果值");
                    HuiLvAbilitySlice.this.ansmo.setHintColor(Color.GRAY);
                    HuiLvAbilitySlice.dw2 = HuiLvAbilitySlice.this.dw;
                    Text ans1 = (Text) HuiLvAbilitySlice.this.findComponentById(ResourceTable.Id_gg4_field);
                    if (HuiLvAbilitySlice.dw2 == -1) {
                        HuiLvAbilitySlice.dw2 = 1;
                        ans1.setText(HuiLvAbilitySlice.stringTitle[HuiLvAbilitySlice.dw2]);
                    } else ans1.setText(HuiLvAbilitySlice.stringTitle[HuiLvAbilitySlice.dw2]);
                    HuiLvAbilitySlice.panduan = 3;
                }
            });//gg3
            this.findComponentById(ResourceTable.Id_jcal_button).setClickedListener(new Component.ClickedListener() {
                @Override
                public void onClick(Component v) {
                    Text ysdw = (Text) HuiLvAbilitySlice.this.findComponentById(ResourceTable.Id_gg2_field);//原数单位
                    Text zhhdw = (Text) HuiLvAbilitySlice.this.findComponentById(ResourceTable.Id_gg4_field);//转换后单位
                    XLog.info(HuiLvAbilitySlice.label, HuiLvAbilitySlice.this.quemo.getText() + " : " + ysdw.getText() + " : " + zhhdw.getText());
                    if (HuiLvAbilitySlice.this.quemo.getText().equals("原数值")) {
                        HuiLvAbilitySlice.this.quemo.setText("");
                        HuiLvAbilitySlice.this.ansmo.setHintColor(Color.RED);
                        HuiLvAbilitySlice.this.ansmo.setHint("未输入原数据!");
                    } else if (ysdw.getText().equals("原数单位") || zhhdw.getText().equals("结果单位"))
                        if (zhhdw.getText().equals("结果单位")) if (ysdw.getText().equals("原数单位")) {
                            HuiLvAbilitySlice.this.quemo.setText("");
                            HuiLvAbilitySlice.this.ansmo.setHintColor(Color.RED);
                            HuiLvAbilitySlice.this.ansmo.setHint("未选择转换前后的单位!");
                        } else {
                            HuiLvAbilitySlice.this.quemo.setText("");
                            HuiLvAbilitySlice.this.ansmo.setHintColor(Color.RED);
                            HuiLvAbilitySlice.this.ansmo.setHint("未选择转换后单位!");
                        }
                        else {
                            HuiLvAbilitySlice.this.quemo.setText("");
                            HuiLvAbilitySlice.this.ansmo.setHintColor(Color.RED);
                            HuiLvAbilitySlice.this.ansmo.setHint("未选择原数据单位!");
                        }
                    else if (HuiLvAbilitySlice.isDecimal(HuiLvAbilitySlice.this.quemo.getText()))
                        HuiLvAbilitySlice.this.GetMethod(String.valueOf(HuiLvAbilitySlice.this.quemo.getText()), String.valueOf(ysdw.getText()), String.valueOf(zhhdw.getText()), "boc");
                    else {
                        HuiLvAbilitySlice.this.quemo.setText("");
                        HuiLvAbilitySlice.this.ansmo.setHintColor(Color.RED);
                        HuiLvAbilitySlice.this.ansmo.setHint("原数据输入错误!");
                    }
                    HuiLvAbilitySlice.panduan = 1;
                }
            });//计算
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * Show dialog.
     *
     * @param text1 the text 1
     */
    private void ShowDialog(String text1) {
        try {
            ohos.data.distributed.device.DeviceInfo localDeviceInfo = KvManagerFactory.getInstance()
                    .createKvManager(new KvManagerConfig((this))).getLocalDeviceInfo();
            int localDeviceType = Integer.parseInt(localDeviceInfo.getType());
            if (localDeviceType == DeviceInfo.DeviceType.PHONE.value()) {
                new MyToastDialog(this.getContext(), text1, ResourceTable.Graphic_xtoast_framem, 36, 25)
                        .setDuration(90)
                        .setAlignment(LayoutAlignment.BOTTOM)
                        .setOffset(0, 100)
                        .show();
                XLog.info(label, "当前设备类型为手机");
            } else if (localDeviceType == DeviceInfo.DeviceType.TABLET.value()) {
                new MyToastDialog(this.getContext(), text1, ResourceTable.Graphic_xtoast_framet, 43, 37)
                        .setDuration(90)
                        .setAlignment(LayoutAlignment.BOTTOM)
                        .setOffset(0, 100)
                        .show();
                XLog.info(label, "当前设备类型为平板");
            } else {
                XLog.warn(label, "暂不支持您的设备:(" + localDeviceInfo.getType() + ")");
                this.terminateAbility();
            }
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * Show dialog 1.
     *
     * @param text1 the text 1
     */
    private void ShowDialog1(String text1) {
        try {
            ohos.data.distributed.device.DeviceInfo localDeviceInfo = KvManagerFactory.getInstance()
                    .createKvManager(new KvManagerConfig((this))).getLocalDeviceInfo();
            int localDeviceType = Integer.parseInt(localDeviceInfo.getType());
            if (localDeviceType == DeviceInfo.DeviceType.PHONE.value()) {
                new MyToastDialog(this, text1, ResourceTable.Graphic_xtoast_framem, 36, 25)
                        .setDuration(23)
                        .setAlignment(LayoutAlignment.BOTTOM)
                        .setOffset(0, 100)
                        .show();
                XLog.info(label, "当前设备类型为手机");
            } else if (localDeviceType == DeviceInfo.DeviceType.TABLET.value()) {
                new MyToastDialog(this.getContext(), text1, ResourceTable.Graphic_xtoast_framet, 43, 37)
                        .setDuration(23)
                        .setAlignment(LayoutAlignment.BOTTOM)
                        .setOffset(0, 100)
                        .show();
                XLog.info(label, "当前设备类型为平板");
            } else XLog.warn(label, "暂不支持您的设备:(" + localDeviceInfo.getType() + ")");
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * Show dialog 2.
     *
     * @param text1 the text 1
     */
    private void ShowDialog2(String text1) {
        try {
            ohos.data.distributed.device.DeviceInfo localDeviceInfo = KvManagerFactory.getInstance()
                    .createKvManager(new KvManagerConfig((this))).getLocalDeviceInfo();
            int localDeviceType = Integer.parseInt(localDeviceInfo.getType());
            if (localDeviceType == DeviceInfo.DeviceType.PHONE.value()) {
                new MyToastDialog(this, text1, ResourceTable.Graphic_xtoast_frame1m, 36, 25)
                        .setDuration(23)
                        .setAlignment(LayoutAlignment.BOTTOM)
                        .setOffset(0, 100)
                        .show();
                XLog.info(label, "当前设备类型为手机");
            } else if (localDeviceType == DeviceInfo.DeviceType.TABLET.value()) {
                new MyToastDialog(this.getContext(), text1, ResourceTable.Graphic_xtoast_frame1t, 43, 37)
                        .setDuration(23)
                        .setAlignment(LayoutAlignment.BOTTOM)
                        .setOffset(0, 100)
                        .show();
                XLog.info(label, "当前设备类型为平板");
            } else XLog.warn(label, "暂不支持您的设备:(" + localDeviceInfo.getType() + ")");
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * 移动
     *
     * @param component  the component
     * @param touchEvent the touch event
     * @return boolean boolean
     */
    @Override
    public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
        try {
            int action = touchEvent.getAction();
            if (action == TouchEvent.PRIMARY_POINT_DOWN) {
                MmiPoint position = touchEvent.getPointerPosition(0);
                this.starx = position.getX();
                this.stary = position.getY();
            } else if (action == TouchEvent.PRIMARY_POINT_UP) {
                MmiPoint position = touchEvent.getPointerPosition(0);
                this.endx = position.getX();
                this.endy = position.getY();
                if (this.starx > this.endx && Math.abs(this.stary - this.endy) < 123 && Math.abs(this.starx - this.endx) > 156) {
                    this.ShowDialog("到头了...");
                    XLog.info(label, "左滑了");
                } else if (this.starx < this.endx && Math.abs(this.stary - this.endy) < 123 && Math.abs(this.starx - this.endx) > 156) {
                    /*无参--页面跳转开始*/
                    Intent intent = new Intent();
                    Operation operation = new Intent.OperationBuilder()
                            .withDeviceId("")
                            .withBundleName(this.getBundleName())
                            .withAbilityName("com.xcl.calculator.Ability.Calculate.CalMenuAbility")
                            .build();// 通过Intent中的OperationBuilder类构造operation对象，指定设备标识（空串表示当前设备）、应用包名、Ability名称
                    intent.setOperation(operation);// 把operation设置到intent中
                    this.startAbility(intent);
                    this.onBackPressed();
                    /*页面跳转结束--无参*/
                    XLog.info(label, "右滑了");
                } else //this.ShowDialog("到头了...");
                    if (this.stary > this.endy && Math.abs(this.starx - this.endx) < 123 && Math.abs(this.stary - this.endy) > 156)
                        XLog.info(label, "上滑了");
                    else //this.ShowDialog("到头了...");
                        if (this.stary < this.endy && Math.abs(this.starx - this.endx) < 123 && Math.abs(this.stary - this.endy) > 156)
                            XLog.info(label, "下滑了");
                        else XLog.info(label, "无效滑动（请直一点！）");
            } else XLog.info(label, "滑动中");
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
        return true;
    }

    /**
     * On stop.
     */
    @Override
    protected void onStop() {
        super.onStop();
        // 移除监听
        if (this.netManager != null) this.netManager.removeNetStatusCallback(this.mNetStatusCallback);
    }

    /**
     * Prepare buttons.
     */
    private void prepareButtons() {
        try {
            int[] direct_button = {
                    ResourceTable.Id_gnumber0_button,//0
                    ResourceTable.Id_gnumber1_button,//1
                    ResourceTable.Id_gnumber2_button,//2
                    ResourceTable.Id_gnumber3_button,//3
                    ResourceTable.Id_gnumber4_button,//4
                    ResourceTable.Id_gnumber5_button,//5
                    ResourceTable.Id_gnumber6_button,//6
                    ResourceTable.Id_gnumber7_button,//7
                    ResourceTable.Id_gnumber8_button,//8
                    ResourceTable.Id_gnumber9_button,//9
                    ResourceTable.Id_gnumberd_button,//.
            };
            for (int id : direct_button)
                this.findComponentById(id).setClickedListener(new Component.ClickedListener() {
                    @Override
                    public void onClick(Component v) {
                        HuiLvAbilitySlice.this.ansmo.setHint("结果值");
                        HuiLvAbilitySlice.this.ansmo.setHintColor(Color.GRAY);
                        if (HuiLvAbilitySlice.panduan >= 0 && HuiLvAbilitySlice.panduan <= 4) {
                            HuiLvAbilitySlice.this.quemo.setText(((Button) v).getText());
                            HuiLvAbilitySlice.panduan = 5;
                        } else
                            HuiLvAbilitySlice.this.quemo.setText(HuiLvAbilitySlice.this.quemo.getText() + ((Button) v).getText());

                    }
                });
        } catch (Exception e) {
            AGConnectCrash.getInstance().recordException(e);
            XLog.error(label, e.getMessage());
        }
    }

    /**
     * On back pressed.
     */
    @Override
    public void onBackPressed() {
        super.onBackPressed();
        this.terminateAbility();
    }

    /**
     * On key down boolean.
     *
     * @param keyCode  the key code
     * @param keyEvent the key event
     * @return the boolean
     */
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent keyEvent) {
        if (keyCode == KeyEvent.KEY_BACK) {
            this.ShowDialog("程序退出成功，感谢您的使用!");
            this.terminateAbility();
            return true;
        }
        return super.onKeyDown(keyCode, keyEvent);
    }

}
